package com.zlzxm.zutil.ui.zwebview;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;

import com.zlzxm.zutil.R;
import com.zlzxm.zutil.ui.activity.ZBaseAbsActivity;
import com.zlzxm.zutil.ui.widget.simplehead.SimpleHead;

/**
 * Created by zlz
 * on  2019/7/10
 */
public class ZWebActivity extends ZBaseAbsActivity {


    public final  static  String TAG_URL = "url";

    public final  static  String TAG_ISOPENBYNEWACTIVITY = "isStartNewActivity";

    public final  static  String TAG_ISSHOWTITLE = "isshowtitle";

    public final  static  String  TAG_TITLE = "title";

    public final  static  String  TAG_STATUSBAR = "statusbar";

    protected RelativeLayout mRlContent;

    protected SimpleHead mSimpleHead = null;

    protected ProgressBar mPb = null;

    protected WebView mWb;

    private String startUlr;

    private String title;

    private boolean isStartNewActivity = false;

    private boolean isshowtitle = false;

    private boolean needStatusBar = false;

    protected ZRoot zRoot = null;

    public static void start(Context context,String url, boolean isStartNewActivity,boolean isshowtitle,String title,boolean needStatusBar){

        Intent intent = new Intent(context,ZWebActivity.class);

        intent.putExtra(TAG_URL,url);
        intent.putExtra(TAG_TITLE,title);

        intent.putExtra(TAG_ISOPENBYNEWACTIVITY,isStartNewActivity);
        intent.putExtra(TAG_ISSHOWTITLE,isshowtitle);
        intent.putExtra(TAG_STATUSBAR,needStatusBar);

        context.startActivity(intent);

    }



    @Override
    protected Object initContentView() {
        return R.layout.activity_web;
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {

        if(needStatusBar){

            setStatusBarTransparent();

        }else {


        }

        mRlContent = findViewById(R.id.rlContent);

        mSimpleHead = findViewById(R.id.sh);

        mWb = new WebView(getApplicationContext());

        mPb = findViewById(R.id.pb);

        if(isshowtitle){

            mSimpleHead.setVisibility(ViewGroup.VISIBLE);

            toolgetherSimpleHead(R.id.sh);

        }else {

            mSimpleHead.setVisibility(ViewGroup.GONE);
            if(title != null) {
                mSimpleHead.setTitle(title);
            }
        }

        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(-1,-1);
        mRlContent.addView(mWb,1,layoutParams);


        WebSettings webSettings = mWb.getSettings();

        //如果访问的页面中要与Javascript交互，则webview必须设置支持Javascript
        webSettings.setJavaScriptEnabled(true);
        // 若加载的 html 里有JS 在执行动画等操作，会造成资源浪费（CPU、电量）
        // 在 onStop 和 onResume 里分别把 setJavaScriptEnabled() 给设置成 false 和 true 即可


        //设置自适应屏幕，两者合用
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小

        //缩放操作
        webSettings.setSupportZoom(true); //支持缩放，默认为true。是下面那个的前提。
        webSettings.setBuiltInZoomControls(true); //设置内置的缩放控件。若为false，则该WebView不可缩放
        webSettings.setDisplayZoomControls(false); //隐藏原生的缩放控件

        //其他细节操作
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE); //关闭webview中缓存
        webSettings.setAllowFileAccess(true); //设置可以访问文件
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true); //支持通过JS打开新窗口
        webSettings.setLoadsImagesAutomatically(true); //支持自动加载图片
        webSettings.setDefaultTextEncodingName("utf-8");//设置编码格式

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            webSettings
                    .setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        //缓存模式如下：
        //LOAD_CACHE_ONLY: 不使用网络，只读取本地缓存数据
        //LOAD_DEFAULT: （默认）根据cache-control决定是否从网络上取数据。
        //LOAD_NO_CACHE: 不使用缓存，只从网络获取数据.
        //LOAD_CACHE_ELSE_NETWORK，只要本地有，无论是否过期，或者no-cache，都使用缓存中的数据。


        mWb.loadUrl(startUlr);

        mWb.setWebViewClient(new MyWebViewClient());

        mWb.setWebChromeClient(new MyWebChromeClient());

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void beforeLoadContentView(Bundle savedInstanceState) {

        startUlr = getIntent().getStringExtra(TAG_URL);
        isStartNewActivity = getIntent().getBooleanExtra(TAG_ISOPENBYNEWACTIVITY,false);
        isshowtitle = getIntent().getBooleanExtra(TAG_ISSHOWTITLE,false);
        title = getIntent().getStringExtra(TAG_TITLE);
        needStatusBar = getIntent().getBooleanExtra(TAG_STATUSBAR,false);



    }



    class  MyWebViewClient extends WebViewClient{

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error){
            handler.proceed();
        }


        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {


            try {
                if(url.startsWith("weixin://") || url.startsWith("alipays://") ||
                        url.startsWith("mailto://") || url.startsWith("tel://")
                    //其他自定义的scheme
                ) {
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }
            } catch (Exception e) { //防止crash (如果手机上没有安装处理某个scheme开头的url的APP, 会导致crash)
                return false;
            }

            if(zRoot != null){

                if(zRoot.shouldOverrideUrlLoading(view,url)){


                    return true;
                }


            }

            if(isStartNewActivity){


                return true;

            }else {

                view.loadUrl(url);

                return true;
            }


        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mPb.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mPb.setVisibility(View.GONE);
        }
    }

    class MyWebChromeClient extends WebChromeClient{

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
            mPb.setProgress(newProgress);

        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);

            if(isshowtitle && title == null){

                mSimpleHead.setTitle(title);
            }

        }
    }

    protected void onDestroy() {
        if (mWb != null) {
            mWb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            mWb.clearHistory();

            ((ViewGroup) mWb.getParent()).removeView(mWb);
            mWb.destroy();
            mWb = null;
        }
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && mWb.canGoBack()) {
            mWb.goBack();
            return true;
        }

        return super.onKeyDown(keyCode, event);
    }

}
